<template>
  <div class="UserBody">
    <div class="UserQuery">
      <el-button type="primary" @click="showaddstatus">添加用户</el-button>
      <el-input v-model="query" placeholder="search Username" @input="UserQuery()" />
    </div>
    <div class="UserTable">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序列" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="180" align="center" />
        <el-table-column prop="email" label="邮箱" width="200" align="center" />
        <el-table-column label="头像" align="center">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px" :preview-teleported='true' :src="scope.row.head_src" :preview-src-list="[scope.row.head_src]"/>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="状态" align="center" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.is_staff" @change="onChanageStatus(scope.row.id, scope.row.is_staff)" />
          </template>
        </el-table-column>
        <el-table-column prop="sign_time" label="最后登录时间" align="center">
          <template #default="slot">
            {{ slot.row.last_login!==null ? $filters.dateformat(slot.row.last_login):'无' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="warning" @click="editUserInfo(scope.row)">修改</el-button>
            <el-button type="danger" @click="removeUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:currentPage="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        small="false"
        background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加、修改对话框 -->
    <el-dialog v-model="addstatus" :title="!addupstatus ? '添加用户' : '修改用户'" width="50%">
      <el-form ref="formRef" destroy-on-close :rules="rules" :model="formInline">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formInline.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="账号名" prop="username">
          <el-input v-model="formInline.username" placeholder="请输入账号名" />
        </el-form-item>
        <el-form-item v-if="!addupstatus" label="密码" prop="password">
          <el-input v-model="formInline.password" type="password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item v-if="!addupstatus" label="角色" prop="roleName">
          <el-select v-model="formInline.roleName" :change="selectChange" class="m-2" placeholder="请选择角色">
            <el-option v-for="item in rloeList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formInline.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="上传头像" prop="head_src">
          <el-upload ref="uploadRef" class="upload-demo" name="head_src" :before-upload="beforeAvatarUpload">
            <el-button type="primary">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">jpg/png files with a size less than 500KB.</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="q">取消</el-button>
          <el-button v-if="!addupstatus" type="primary" @click="addUser(formRef)">添加</el-button>
          <el-button v-else type="primary" @click="subupDate()">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
// import { Plus } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from 'vue'
import type { FormInstance } from 'element-plus'
import Service from './api/users'

export default {
  setup() {
    const token = `Bearer ${sessionStorage.getItem('accessToken')}`
    const { proxy }:any = getCurrentInstance()
    const formRef = ref<FormInstance>()
    const addupstatus = ref(false)
    const addstatus = ref(false)
    const name = ref('')
    const uploadRef = ref()

    // 计数器
    const count = ref(0)
    const data = reactive({
      tableData: [],
      rloeList: [],
      formInline:<any>{
        username: '',
        nickname: '',
        password: '',
        email: '',
        roleName: [],
        head_src: '' // 文件
      }
    })
    const resetForm = (formEl: FormInstance | undefined) => {
      addstatus.value = false
      if (!formEl) return
      formEl.resetFields()
    }

    const rules = reactive({
      username: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 32, message: 'Length should be 3 to 5', trigger: 'blur' }
      ],
      nickname: [{ required: true, message: 'Please input Activity nickname', trigger: 'blur' }],
      password: [{ required: true, message: 'Please input Activity password', trigger: 'blur' }],
      email: [{ required: true, message: 'Please input Activity email', trigger: 'blur' }],
      roleName: [{ required: true, message: 'Please input Activity roleName', trigger: 'blur' }]
      // head_src:[
      //   { required: true, message: 'Please input Activity head_src', trigger: 'blur' },
      // ],
    })
    const currentPage = ref(10)
    const pageSize = ref(5)
    const pageNum = ref(1)
    const query = ref('')

    const UserList = async () => {
      const info = { nickname: query.value, pagesize: pageSize.value, pagenum: pageNum.value }
      const res = await Service.getUserList(info)
      data.tableData = res.data
      currentPage.value = res.count
      pageNum.value = res.pagenum
      console.log(res)
    }
    const GetRoleList = async () => {
      const rolelist = await Service.getRoleList()
      data.rloeList = rolelist
    }
    const showaddstatus = () => {
      data.formInline = {}
      addupstatus.value = false
      addstatus.value = true
      if (count.value === 0) {
        GetRoleList()
      }
      count.value += 1
    }

    const beforeAvatarUpload = (file: any) => {
      data.formInline.head_src = file
      return false
    }
    const q = () => {
      addstatus.value = false
      console.log(data.formInline)
    }

    onMounted(UserList)

    // 选中值发生变化
    const selectChange = (e: any) => {
      data.formInline.roleName = [e]
    }
    // 切换每页显示多少条
    const handleSizeChange = (val: number) => {
      pageSize.value = val
      UserList()
    }
    // 切换第几页
    const handleCurrentChange = (val: number) => {
      pageNum.value = val
      UserList()
    }
    // 修改用户信息
    const editUserInfo = async (val: object) => {
      addupstatus.value = true
      addstatus.value = true
      data.formInline = { ...val }
    }

    const UserQuery = () => {
      UserList()
    }


    const onChanageStatus = async (id: any, status: any) => {
      const res = await Service.UpdateUser(id, { is_staff: status })
      if (!res.id) return proxy.$message.error('修改状态失败')
      proxy.$message.success('修改状态成功')
      return {}
    }

    const subupDate = async () => {
      const { nickname, username, email, head_src } = data.formInline
      const upshu = <any>{ nickname, username, email, head_src }
      const formdata = new FormData()
      for (const key in upshu) {
        if (key === 'head_src' && upshu[`${key}`] === null) continue
        formdata.append(`${key}`, upshu[`${key}`])
      }
      console.log(upshu)

      const res = await Service.UpdateUser(data.formInline.id, formdata)
      if (!res.id) return proxy.$message.error('修改失败')
      proxy.$message.success('修改成功')
      UserList()
      addstatus.value = false
    }

    // 添加用户
    const addUser = (form: any) => {
      form.validate(async (mm: any) => {
        if (!mm) return proxy.$message.error('验证未通过')
        const formdata = new FormData()
        // formdata.append('name','aaaa')
        for (const key in data.formInline) {
          formdata.append(`${key}`, data.formInline[`${key}`])
        }
        const res = await Service.AddUser(formdata)
        if (!res.id) return proxy.$message.error('添加失败')
        proxy.$message.success('添加成功')
        UserList()
        addstatus.value = false
      })
    }
    // 删除用户信息
    const removeUser = async (index: Number) => {
      await Service.DelUserInfo(index)
      UserList()
    }

    return {
      name,
      pageNum,
      query,
      addstatus,
      addupstatus,
      ...toRefs(data),
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange,
      editUserInfo,
      removeUser,
      UserQuery,
      // formInline,
      rules,
      formRef,
      resetForm,
      beforeAvatarUpload,
      // fileList,
      GetRoleList,
      showaddstatus,
      addUser,
      selectChange,
      uploadRef,
      token,
      subupDate,
      q,
      onChanageStatus,
    }
  }
}
</script>

<style lang="stylus" scoped>

.UserBody {
  position relative
  width: 100%;
  padding-left: 2%;
  padding-right: 2%;
  box-sizing: border-box;
  .UserQuery{
    text-align: left;
    .el-input{
      width: 300px;
      margin-left: 2%;
    }
  }
  .UserTable{
    width:100%;
    height: 100%;
    margin-top: 2%;
  }
  .pagination{
    width: 100%;
    padding: 20px 0 0 25%;
  }
}
.el-dialog{
  margin-top: 10% !important;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
